import React, { useState, useEffect } from 'react';
import { is_empty, obj_str, Info, GridTable, ck_float, to_float, cline, useKForm, KInput, useCmd, WaitUmd, MainView, KFind,
    obj_int, alert_st, KSwitch, CkUsn, uReal, useHigh, ck_empty, PanelTitle, Btn, loc } from 'sui';
import { useAccess } from 'cache';
import { save_auto, reload_auto, load_tech, load_mt } from '../cmd';
import { get_alert } from '../cmd';
import { BindMt } from './mt';

const AutoView = () => {
    const [alert, setAlert] = useState();
    const [open_info, openInfo] = useState(false);
    const [main, setMain] = useState();
    const [cera_lst, ceraLst] = useState();
    const [stell_lst, stellLst] = useState();
    const [dw_lst, dwLst] = useState();
    const [no_acc] = useAccess();
    const umd = useCmd();
    const [high] = useHigh(252, 100);
    const form = useKForm(null, {
        diff: 1,
        w: 0.5,
        range: 1,
    });

    useEffect(() => {
        get_alert(setAlert);
        load_tech(dwLst);
        load_mt("cera", ceraLst);
        load_mt("stell", stellLst);
    }, []);

    useEffect(() => {
        if (is_empty(dw_lst) || is_empty(cera_lst) || is_empty(stell_lst)) {
            return;
        }

        reload_auto(null, form, setMain);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [stell_lst, cera_lst, dw_lst]);

    const hret = () => {
        umd.hreturn();

        reload_auto(null, form, setMain);
    };

    const getBatch = () => {
        if (main) {
            return main["batch"];
        }

        return null;
    };

    const getMt = () => {
        const sn = form.get("tsn");
        if (!sn) {
            return null;
        }

        const f = dw_lst.find(d => d.sn === sn);
        if (!f) {
            return null;
        }

        const ball = obj_str(f, "val");

        const mt = obj_str(f, "mt");
        let lst = mt === "T" ? cera_lst : stell_lst;

        lst = lst.filter(d => d.ball === ball);

        return lst;
    };

    const getTech = () => {
        const sn = form.get("tsn");
        if (!sn) {
            return null;
        }

        const f = dw_lst.find(d => d.sn === sn);
        if (!f) {
            return null;
        }

        return f;
    };

    if (umd.isFin("batch")) {
        return <BindMt hreturn={hret} mt={getMt()} data={main} cur={getTech()} alert={alert}/>;
    }

    const hSave = (start) => {
        const ck = {
            w: v => ck_float(v),
            diff: v => ck_float(v),
            base: v => ck_float(v),
            range: v => ck_float(v),
            tsn: v => ck_empty(v),
            dmin: v => ck_float(v),
            dmax: v => {
                const e = ck_float(v);
                if (e) {
                    return e;
                }

                const a = to_float(form.get("dmin"));
                const b = to_float(form.get("dmax"));

                if (b < a) {
                    return loc("l_705");
                }

                return null;
            },
            kmin: v => ck_float(v),
            kmax: v => {
                const e = ck_float(v);
                if (e) {
                    return e;
                }

                const a = to_float(form.get("kmin"));
                const b = to_float(form.get("kmax"));

                if (b < a) {
                    return loc("l_705");
                }

                return null;
            },
            other: v => {
                const ck_other = form.get("ck_other");
                if (ck_other !== "Y") {
                    return null;
                }

                let tsn = form.get("tsn");
                tsn = tsn.split("-");

                let stsn = v.split("-");

                if (tsn[0] !== stsn[0]) {
                    return loc("l_846");
                }

                return null;
            }
        };

        if (form.isErr(ck)) {
            return;
        }

        umd.startWait();

        const tsn = form.get("tsn");
        let mt = "";
        let ball = "";
        let ball_num = "";

        let f = dw_lst.find(d => d.sn === tsn);
        if (f) {
            mt = obj_str(f, "mt");
            ball = obj_str(f, "val");
            ball_num = obj_int(f, "num");
        }

        const opt = {
            w: to_float(form.get("w")),
            diff: to_float(form.get("diff")),
            base: to_float(form.get("base")),
            range: to_float(form.get("range")),
            tsn: tsn,
            mt: mt,
            ball: to_float(ball),
            num: ball_num,
            dmin: to_float(form.get("dmin")),
            dmax: to_float(form.get("dmax")),
            kmin: to_float(form.get("kmin")),
            kmax: to_float(form.get("kmax")),
            other: "",
        };

        const ck_other = form.get("ck_other");
        if (ck_other === "Y") {
            opt["other"] = form.get("other");
        }

        const doSave = () => {
            save_auto(opt,
                () => reload_auto(() => umd.endWait(loc("l_240")), form, setMain),
                () => umd.setErr());
        };

        if (start) {
            uReal(null, "auto/start", {
                line: cline(),
                k: tsn,
            },
            r => doSave(),
            e => umd.setErr());
        } else {
            doSave();
        }
    };

    const col = [
        {sn: "tsn", name: loc("l_694")},
        {sn: "mt", name: loc("l_738")},
        {sn: "ball", name: loc("l_714")},
        {sn: "num", name: loc("l_717")},
        {sn: "diff", name: loc("l_693")},
        {sn: "w", name: loc("l_692")},
        {sn: "base", name: `${loc("l_695")}-${loc("l_699")}`},
        {sn: "range", name: `${loc("l_695")}-${loc("l_700")}`},
        {sn: "dmin", name: `${loc("l_690")}-${loc("l_696")}`},
        {sn: "dmax", name: `${loc("l_690")}-${loc("l_646")}`},
        {sn: "kmin", name: `${loc("l_691")}-${loc("l_696")}`},
        {sn: "kmax", name: `${loc("l_691")}-${loc("l_646")}`},
        {sn: "other", name: loc("l_845")},
    ];

    const batchcol = [
        {name: loc("l_488"), key: 'sn', width: 300},
        {name: loc("l_715"), key: 'std', width: 100},
        {name: loc("l_801"), key: 'sub', width: 100},
        {name: loc("l_802"), key: 'dw', width: 100},
        {name: loc("l_131"), key: 'st', width: 70, formatter: (props) => {
            const d = props.row;
            return alert_st(d, alert);
        }},
        {name: loc("l_127"), key: 'num', width: 100},
    ];

    return (
        <MainView>
            <PanelTitle left={loc("l_737")} cl="gray">
                <div className="flex flex-row">
                    <Btn className="mr-4 mb-6 mt-2" color="teal" disabled={no_acc("dd")} hcmd={() => openInfo(true)}>{loc("l_866")}</Btn>
                    <Btn className="mr-4 mb-6 mt-2" color="green" disabled={no_acc("dd")} hcmd={() => hSave(false)}>{loc("l_234")}</Btn>
                    <div className="flex flex-col mb-4">
                        <div className="inline-flex">
                            <KFind label={loc("l_694")} form={form} name="tsn" margin="dense" width="w-56" list={dw_lst} c2={loc("l_738")}/>
                            <KInput label={loc("l_693")} form={form} name="diff" mg="dense" width="w-20" className="mx-4"/>
                            <KInput label={loc("l_692")} form={form} name="w" mg="dense" width="w-20"/>
                            <div className="inline-flex items-center mx-4 px-2 border-blue-600 border">
                                <span className="text-base mr-4 mt-1">{loc("l_695")}</span>
                                <KInput label={loc("l_699")} form={form} name="base" mg="dense" width="w-20"/>
                                <span className="text-base mx-4">{"+/-"}</span>
                                <KInput label={loc("l_700")} form={form} name="range" mg="dense" width="w-20"/>
                            </div>
                            <div className="inline-flex items-center px-2 border-blue-600 border">
                                <span className="text-base mr-4 mt-1">{loc("l_690")}</span>
                                <KInput label={loc("l_696")} form={form} name="dmin" mg="dense" width="w-20"/>
                                <KInput label={loc("l_646")} form={form} name="dmax" mg="dense" width="w-20" className="ml-2"/>
                            </div>
                            <div className="inline-flex items-center px-2 ml-4 border-blue-600 border">
                                <span className="text-base mr-4 mt-1">{loc("l_691")}</span>
                                <KInput label={loc("l_696")} form={form} name="kmin" mg="dense" width="w-20"/>
                                <KInput label={loc("l_646")} form={form} name="kmax" mg="dense" width="w-20" className="ml-2"/>
                            </div>
                        </div>
                        <div className="inline-flex mt-4 items-center">
                            <Btn disabled={!form.get("tsn")} className="mr-4" hcmd={() => umd.pact(null, null, "batch")}>{loc("l_488")}</Btn>
                            <KSwitch form={form} name="ck_other" className="mr-4">{loc("l_845")}</KSwitch>
                            <KFind label={loc("l_694")} form={form} name="other" margin="dense" width="w-56" list={dw_lst}
                                disabled={form.get("ck_other") !== "Y"}/>
                        </div>
                    </div>
                </div>
            </PanelTitle>
            <div className="w-full flex flex-row">
                <div className="w-1/3">
                    <Info col={col} data={main} className="ml-4 text-xl"/>
                </div>
                <div className="w-2/3">
                    <PanelTitle cl="blue" left={loc("l_817")}/>
                    <GridTable col={batchcol} row={getBatch()} high={high}/>
                </div>
            </div>
            <CkUsn open={open_info} setOpen={openInfo} msg={loc("l_871")} hcmd={() => hSave(true)}/>
            <WaitUmd umd={umd}/>
        </MainView>
    );
};

export {AutoView};
